home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / unittest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  40.5 KB  |  855 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. '''
  5. Python unit testing framework, based on Erich Gamma\'s JUnit and Kent Beck\'s
  6. Smalltalk testing framework.
  7.  
  8. This module contains the core framework classes that form the basis of
  9. specific test cases and suites (TestCase, TestSuite etc.), and also a
  10. text-based utility class for running the tests and reporting the results
  11.  (TextTestRunner).
  12.  
  13. Simple usage:
  14.  
  15.     import unittest
  16.  
  17.     class IntegerArithmenticTestCase(unittest.TestCase):
  18.         def testAdd(self):  ## test method names begin \'test*\'
  19.             self.assertEquals((1 + 2), 3)
  20.             self.assertEquals(0 + 1, 1)
  21.         def testMultiply(self):
  22.             self.assertEquals((0 * 10), 0)
  23.             self.assertEquals((5 * 8), 40)
  24.  
  25.     if __name__ == \'__main__\':
  26.         unittest.main()
  27.  
  28. Further information is available in the bundled documentation, and from
  29.  
  30.   http://pyunit.sourceforge.net/
  31.  
  32. Copyright (c) 1999, 2000, 2001 Steve Purcell
  33. This module is free software, and you may redistribute it and/or modify
  34. it under the same terms as Python itself, so long as this copyright message
  35. and disclaimer are retained in their original form.
  36.  
  37. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  38. SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  39. THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  40. DAMAGE.
  41.  
  42. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  43. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  44. PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  45. AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  46. SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  47. '''
  48. __author__ = 'Steve Purcell'
  49. __email__ = 'stephen_purcell at yahoo dot com'
  50. __version__ = '#Revision: 1.46 $'[11:-2]
  51. import time
  52. import sys
  53. import traceback
  54. import string
  55. import os
  56. import types
  57. __metaclass__ = type
  58.  
  59. def _strclass(cls):
  60.     return '%s.%s' % (cls.__module__, cls.__name__)
  61.  
  62.  
  63. class TestResult:
  64.     '''Holder for test result information.
  65.  
  66.     Test results are automatically managed by the TestCase and TestSuite
  67.     classes, and do not need to be explicitly manipulated by writers of tests.
  68.  
  69.     Each instance holds the total number of tests run, and collections of
  70.     failures and errors that occurred among those test runs. The collections
  71.     contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
  72.     formatted traceback of the error that occurred.
  73.     '''
  74.     
  75.     def __init__(self):
  76.         self.failures = []
  77.         self.errors = []
  78.         self.testsRun = 0
  79.         self.shouldStop = 0
  80.  
  81.     
  82.     def startTest(self, test):
  83.         '''Called when the given test is about to be run'''
  84.         self.testsRun = self.testsRun + 1
  85.  
  86.     
  87.     def stopTest(self, test):
  88.         '''Called when the given test has been run'''
  89.         pass
  90.  
  91.     
  92.     def addError(self, test, err):
  93.         """Called when an error has occurred. 'err' is a tuple of values as
  94.         returned by sys.exc_info().
  95.         """
  96.         self.errors.append((test, self._exc_info_to_string(err)))
  97.  
  98.     
  99.     def addFailure(self, test, err):
  100.         """Called when an error has occurred. 'err' is a tuple of values as
  101.         returned by sys.exc_info()."""
  102.         self.failures.append((test, self._exc_info_to_string(err)))
  103.  
  104.     
  105.     def addSuccess(self, test):
  106.         '''Called when a test has completed successfully'''
  107.         pass
  108.  
  109.     
  110.     def wasSuccessful(self):
  111.         '''Tells whether or not this result was a success'''
  112.         return None if len(self.errors) == len(self.errors) else len(self.errors) == 0
  113.  
  114.     
  115.     def stop(self):
  116.         '''Indicates that the tests should be aborted'''
  117.         self.shouldStop = 1
  118.  
  119.     
  120.     def _exc_info_to_string(self, err):
  121.         '''Converts a sys.exc_info()-style tuple of values into a string.'''
  122.         return string.join(traceback.format_exception(*err), '')
  123.  
  124.     
  125.     def __repr__(self):
  126.         return '<%s run=%i errors=%i failures=%i>' % (_strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures))
  127.  
  128.  
  129.  
  130. class TestCase:
  131.     """A class whose instances are single test cases.
  132.  
  133.     By default, the test code itself should be placed in a method named
  134.     'runTest'.
  135.  
  136.     If the fixture may be used for many test cases, create as
  137.     many test methods as are needed. When instantiating such a TestCase
  138.     subclass, specify in the constructor arguments the name of the test method
  139.     that the instance is to execute.
  140.  
  141.     Test authors should subclass TestCase for their own tests. Construction
  142.     and deconstruction of the test's environment ('fixture') can be
  143.     implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  144.  
  145.     If it is necessary to override the __init__ method, the base class
  146.     __init__ method must always be called. It is important that subclasses
  147.     should not change the signature of their __init__ method, since instances
  148.     of the classes are instantiated automatically by parts of the framework
  149.     in order to be run.
  150.     """
  151.     failureException = AssertionError
  152.     
  153.     def __init__(self, methodName = 'runTest'):
  154.         '''Create an instance of the class that will use the named test
  155.            method when executed. Raises a ValueError if the instance does
  156.            not have a method with the specified name.
  157.         '''
  158.         
  159.         try:
  160.             self._TestCase__testMethodName = methodName
  161.             testMethod = getattr(self, methodName)
  162.             self._TestCase__testMethodDoc = testMethod.__doc__
  163.         except AttributeError:
  164.             raise ValueError, 'no such test method in %s: %s' % (self.__class__, methodName)
  165.  
  166.  
  167.     
  168.     def setUp(self):
  169.         '''Hook method for setting up the test fixture before exercising it.'''
  170.         pass
  171.  
  172.     
  173.     def tearDown(self):
  174.         '''Hook method for deconstructing the test fixture after testing it.'''
  175.         pass
  176.  
  177.     
  178.     def countTestCases(self):
  179.         return 1
  180.  
  181.     
  182.     def defaultTestResult(self):
  183.         return TestResult()
  184.  
  185.     
  186.     def shortDescription(self):
  187.         """Returns a one-line description of the test, or None if no
  188.         description has been provided.
  189.  
  190.         The default implementation of this method returns the first line of
  191.         the specified test method's docstring.
  192.         """
  193.         doc = self._TestCase__testMethodDoc
  194.         if not doc and string.strip(string.split(doc, '\n')[0]):
  195.             pass
  196.         return None
  197.  
  198.     
  199.     def id(self):
  200.         return '%s.%s' % (_strclass(self.__class__), self._TestCase__testMethodName)
  201.  
  202.     
  203.     def __str__(self):
  204.         return '%s (%s)' % (self._TestCase__testMethodName, _strclass(self.__class__))
  205.  
  206.     
  207.     def __repr__(self):
  208.         return '<%s testMethod=%s>' % (_strclass(self.__class__), self._TestCase__testMethodName)
  209.  
  210.     
  211.     def run(self, result = None):
  212.         return self(result)
  213.  
  214.     
  215.     def __call__(self, result = None):
  216.         if result is None:
  217.             result = self.defaultTestResult()
  218.         
  219.         result.startTest(self)
  220.         testMethod = getattr(self, self._TestCase__testMethodName)
  221.         
  222.         try:
  223.             self.setUp()
  224.         except KeyboardInterrupt:
  225.             raise 
  226.         except:
  227.             result.addError(self, self._TestCase__exc_info())
  228.             return None
  229.         
  230.  
  231.         ok = 0
  232.         
  233.         try:
  234.             testMethod()
  235.             ok = 1
  236.         except self.failureException:
  237.             result.addFailure(self, self._TestCase__exc_info())
  238.         except KeyboardInterrupt:
  239.             raise 
  240.         except:
  241.             result.addError(self, self._TestCase__exc_info())
  242.  
  243.         
  244.         try:
  245.             self.tearDown()
  246.         except KeyboardInterrupt:
  247.             raise 
  248.         except:
  249.             result.addError(self, self._TestCase__exc_info())
  250.             ok = 0
  251.  
  252.         if ok:
  253.             result.addSuccess(self)
  254.         result.stopTest(self)
  255.  
  256.     
  257.     def debug(self):
  258.         '''Run the test without collecting errors in a TestResult'''
  259.         self.setUp()
  260.         getattr(self, self._TestCase__testMethodName)()
  261.         self.tearDown()
  262.  
  263.     
  264.     def __exc_info(self):
  265.         '''Return a version of sys.exc_info() with the traceback frame
  266.            minimised; usually the top level of the traceback frame is not
  267.            needed.
  268.         '''
  269.         (exctype, excvalue, tb) = sys.exc_info()
  270.         if sys.platform[:4] == 'java':
  271.             return (exctype, excvalue, tb)
  272.         
  273.         newtb = tb.tb_next
  274.         if newtb is None:
  275.             return (exctype, excvalue, tb)
  276.         
  277.         return (exctype, excvalue, newtb)
  278.  
  279.     
  280.     def fail(self, msg = None):
  281.         '''Fail immediately, with the given message.'''
  282.         raise self.failureException, msg
  283.  
  284.     
  285.     def failIf(self, expr, msg = None):
  286.         '''Fail the test if the expression is true.'''
  287.         if expr:
  288.             raise self.failureException, msg
  289.         
  290.  
  291.     
  292.     def failUnless(self, expr, msg = None):
  293.         '''Fail the test unless the expression is true.'''
  294.         if not expr:
  295.             raise self.failureException, msg
  296.         
  297.  
  298.     
  299.     def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
  300.         '''Fail unless an exception of class excClass is thrown
  301.            by callableObj when invoked with arguments args and keyword
  302.            arguments kwargs. If a different type of exception is
  303.            thrown, it will not be caught, and the test case will be
  304.            deemed to have suffered an error, exactly as for an
  305.            unexpected exception.
  306.         '''
  307.         
  308.         try:
  309.             callableObj(*args, **kwargs)
  310.         except excClass:
  311.             return None
  312.  
  313.         if hasattr(excClass, '__name__'):
  314.             excName = excClass.__name__
  315.         else:
  316.             excName = str(excClass)
  317.         raise self.failureException, excName
  318.  
  319.     
  320.     def failUnlessEqual(self, first, second, msg = None):
  321.         """Fail if the two objects are unequal as determined by the '=='
  322.            operator.
  323.         """
  324.         if not (first == second):
  325.             if not msg:
  326.                 pass
  327.             raise self.failureException, '%s != %s' % (`first`, `second`)
  328.         
  329.  
  330.     
  331.     def failIfEqual(self, first, second, msg = None):
  332.         """Fail if the two objects are equal as determined by the '=='
  333.            operator.
  334.         """
  335.         if first == second:
  336.             if not msg:
  337.                 pass
  338.             raise self.failureException, '%s == %s' % (`first`, `second`)
  339.         
  340.  
  341.     
  342.     def failUnlessAlmostEqual(self, first, second, places = 7, msg = None):
  343.         '''Fail if the two objects are unequal as determined by their
  344.            difference rounded to the given number of decimal places
  345.            (default 7) and comparing to zero.
  346.  
  347.            Note that decimal places (from zero) is usually not the same
  348.            as significant digits (measured from the most signficant digit).
  349.         '''
  350.         if round(second - first, places) != 0:
  351.             if not msg:
  352.                 pass
  353.             raise self.failureException, '%s != %s within %s places' % (`first`, `second`, `places`)
  354.         
  355.  
  356.     
  357.     def failIfAlmostEqual(self, first, second, places = 7, msg = None):
  358.         '''Fail if the two objects are equal as determined by their
  359.            difference rounded to the given number of decimal places
  360.            (default 7) and comparing to zero.
  361.  
  362.            Note that decimal places (from zero) is usually not the same
  363.            as significant digits (measured from the most signficant digit).
  364.         '''
  365.         if round(second - first, places) == 0:
  366.             if not msg:
  367.                 pass
  368.             raise self.failureException, '%s == %s within %s places' % (`first`, `second`, `places`)
  369.         
  370.  
  371.     assertEqual = assertEquals = failUnlessEqual
  372.     assertNotEqual = assertNotEquals = failIfEqual
  373.     assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
  374.     assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
  375.     assertRaises = failUnlessRaises
  376.     assert_ = failUnless
  377.  
  378.  
  379. class TestSuite:
  380.     '''A test suite is a composite test consisting of a number of TestCases.
  381.  
  382.     For use, create an instance of TestSuite, then add test case instances.
  383.     When all tests have been added, the suite can be passed to a test
  384.     runner, such as TextTestRunner. It will run the individual test cases
  385.     in the order in which they were added, aggregating the results. When
  386.     subclassing, do not forget to call the base class constructor.
  387.     '''
  388.     
  389.     def __init__(self, tests = ()):
  390.         self._tests = []
  391.         self.addTests(tests)
  392.  
  393.     
  394.     def __repr__(self):
  395.         return '<%s tests=%s>' % (_strclass(self.__class__), self._tests)
  396.  
  397.     __str__ = __repr__
  398.     
  399.     def countTestCases(self):
  400.         cases = 0
  401.         for test in self._tests:
  402.             cases = cases + test.countTestCases()
  403.         
  404.         return cases
  405.  
  406.     
  407.     def addTest(self, test):
  408.         self._tests.append(test)
  409.  
  410.     
  411.     def addTests(self, tests):
  412.         for test in tests:
  413.             self.addTest(test)
  414.         
  415.  
  416.     
  417.     def run(self, result):
  418.         return self(result)
  419.  
  420.     
  421.     def __call__(self, result):
  422.         for test in self._tests:
  423.             if result.shouldStop:
  424.                 break
  425.             
  426.             test(result)
  427.         
  428.         return result
  429.  
  430.     
  431.     def debug(self):
  432.         '''Run the tests without collecting errors in a TestResult'''
  433.         for test in self._tests:
  434.             test.debug()
  435.         
  436.  
  437.  
  438.  
  439. class FunctionTestCase(TestCase):
  440.     """A test case that wraps a test function.
  441.  
  442.     This is useful for slipping pre-existing test functions into the
  443.     PyUnit framework. Optionally, set-up and tidy-up functions can be
  444.     supplied. As with TestCase, the tidy-up ('tearDown') function will
  445.     always be called if the set-up ('setUp') function ran successfully.
  446.     """
  447.     
  448.     def __init__(self, testFunc, setUp = None, tearDown = None, description = None):
  449.         TestCase.__init__(self)
  450.         self._FunctionTestCase__setUpFunc = setUp
  451.         self._FunctionTestCase__tearDownFunc = tearDown
  452.         self._FunctionTestCase__testFunc = testFunc
  453.         self._FunctionTestCase__description = description
  454.  
  455.     
  456.     def setUp(self):
  457.         if self._FunctionTestCase__setUpFunc is not None:
  458.             self._FunctionTestCase__setUpFunc()
  459.         
  460.  
  461.     
  462.     def tearDown(self):
  463.         if self._FunctionTestCase__tearDownFunc is not None:
  464.             self._FunctionTestCase__tearDownFunc()
  465.         
  466.  
  467.     
  468.     def runTest(self):
  469.         self._FunctionTestCase__testFunc()
  470.  
  471.     
  472.     def id(self):
  473.         return self._FunctionTestCase__testFunc.__name__
  474.  
  475.     
  476.     def __str__(self):
  477.         return '%s (%s)' % (_strclass(self.__class__), self._FunctionTestCase__testFunc.__name__)
  478.  
  479.     
  480.     def __repr__(self):
  481.         return '<%s testFunc=%s>' % (_strclass(self.__class__), self._FunctionTestCase__testFunc)
  482.  
  483.     
  484.     def shortDescription(self):
  485.         if self._FunctionTestCase__description is not None:
  486.             return self._FunctionTestCase__description
  487.         
  488.         doc = self._FunctionTestCase__testFunc.__doc__
  489.         if not doc and string.strip(string.split(doc, '\n')[0]):
  490.             pass
  491.         return None
  492.  
  493.  
  494.  
  495. class TestLoader:
  496.     '''This class is responsible for loading tests according to various
  497.     criteria and returning them wrapped in a Test
  498.     '''
  499.     testMethodPrefix = 'test'
  500.     sortTestMethodsUsing = cmp
  501.     suiteClass = TestSuite
  502.     
  503.     def loadTestsFromTestCase(self, testCaseClass):
  504.         '''Return a suite of all tests cases contained in testCaseClass'''
  505.         return self.suiteClass(map(testCaseClass, self.getTestCaseNames(testCaseClass)))
  506.  
  507.     
  508.     def loadTestsFromModule(self, module):
  509.         '''Return a suite of all tests cases contained in the given module'''
  510.         tests = []
  511.         for name in dir(module):
  512.             obj = getattr(module, name)
  513.             if isinstance(obj, (type, types.ClassType)) and issubclass(obj, TestCase):
  514.                 tests.append(self.loadTestsFromTestCase(obj))
  515.                 continue
  516.         
  517.         return self.suiteClass(tests)
  518.  
  519.     
  520.     def loadTestsFromName(self, name, module = None):
  521.         '''Return a suite of all tests cases given a string specifier.
  522.  
  523.         The name may resolve either to a module, a test case class, a
  524.         test method within a test case class, or a callable object which
  525.         returns a TestCase or TestSuite instance.
  526.  
  527.         The method optionally resolves the names relative to a given module.
  528.         '''
  529.         parts = string.split(name, '.')
  530.         if module is None:
  531.             if not parts:
  532.                 raise ValueError, 'incomplete test name: %s' % name
  533.             else:
  534.                 parts_copy = parts[:]
  535.                 while parts_copy:
  536.                     
  537.                     try:
  538.                         module = __import__(string.join(parts_copy, '.'))
  539.                     continue
  540.                     except ImportError:
  541.                         del parts_copy[-1]
  542.                         if not parts_copy:
  543.                             raise 
  544.                         
  545.                         not parts_copy
  546.                     
  547.  
  548.                     None<EXCEPTION MATCH>ImportError
  549.                 parts = parts[1:]
  550.         
  551.         obj = module
  552.         for part in parts:
  553.             obj = getattr(obj, part)
  554.         
  555.         import unittest
  556.         if type(obj) == types.ModuleType:
  557.             return self.loadTestsFromModule(obj)
  558.         elif isinstance(obj, (type, types.ClassType)) and issubclass(obj, unittest.TestCase):
  559.             return self.loadTestsFromTestCase(obj)
  560.         elif type(obj) == types.UnboundMethodType:
  561.             return obj.im_class(obj.__name__)
  562.         elif callable(obj):
  563.             test = obj()
  564.             if not isinstance(test, unittest.TestCase) and not isinstance(test, unittest.TestSuite):
  565.                 raise ValueError, 'calling %s returned %s, not a test' % (obj, test)
  566.             
  567.             return test
  568.         else:
  569.             raise ValueError, "don't know how to make test from: %s" % obj
  570.  
  571.     
  572.     def loadTestsFromNames(self, names, module = None):
  573.         """Return a suite of all tests cases found using the given sequence
  574.         of string specifiers. See 'loadTestsFromName()'.
  575.         """
  576.         suites = []
  577.         for name in names:
  578.             suites.append(self.loadTestsFromName(name, module))
  579.         
  580.         return self.suiteClass(suites)
  581.  
  582.     
  583.     def getTestCaseNames(self, testCaseClass):
  584.         '''Return a sorted sequence of method names found within testCaseClass
  585.         '''
  586.         testFnNames = filter((lambda n, p = self.testMethodPrefix: n[:len(p)] == p), dir(testCaseClass))
  587.         for baseclass in testCaseClass.__bases__:
  588.             for testFnName in self.getTestCaseNames(baseclass):
  589.                 if testFnName not in testFnNames:
  590.                     testFnNames.append(testFnName)
  591.                     continue
  592.             
  593.         
  594.         if self.sortTestMethodsUsing:
  595.             testFnNames.sort(self.sortTestMethodsUsing)
  596.         
  597.         return testFnNames
  598.  
  599.  
  600. defaultTestLoader = TestLoader()
  601.  
  602. def _makeLoader(prefix, sortUsing, suiteClass = None):
  603.     loader = TestLoader()
  604.     loader.sortTestMethodsUsing = sortUsing
  605.     loader.testMethodPrefix = prefix
  606.     if suiteClass:
  607.         loader.suiteClass = suiteClass
  608.     
  609.     return loader
  610.  
  611.  
  612. def getTestCaseNames(testCaseClass, prefix, sortUsing = cmp):
  613.     return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
  614.  
  615.  
  616. def makeSuite(testCaseClass, prefix = 'test', sortUsing = cmp, suiteClass = TestSuite):
  617.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  618.  
  619.  
  620. def findTestCases(module, prefix = 'test', sortUsing = cmp, suiteClass = TestSuite):
  621.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
  622.  
  623.  
  624. class _WritelnDecorator:
  625.     """Used to decorate file-like objects with a handy 'writeln' method"""
  626.     
  627.     def __init__(self, stream):
  628.         self.stream = stream
  629.  
  630.     
  631.     def __getattr__(self, attr):
  632.         return getattr(self.stream, attr)
  633.  
  634.     
  635.     def writeln(self, *args):
  636.         if args:
  637.             self.write(*args)
  638.         
  639.         self.write('\n')
  640.  
  641.  
  642.  
  643. class _TextTestResult(TestResult):
  644.     '''A test result class that can print formatted text results to a stream.
  645.  
  646.     Used by TextTestRunner.
  647.     '''
  648.     separator1 = '=' * 70
  649.     separator2 = '-' * 70
  650.     
  651.     def __init__(self, stream, descriptions, verbosity):
  652.         TestResult.__init__(self)
  653.         self.stream = stream
  654.         self.showAll = verbosity > 1
  655.         self.dots = verbosity == 1
  656.         self.descriptions = descriptions
  657.  
  658.     
  659.     def getDescription(self, test):
  660.         if self.descriptions:
  661.             if not test.shortDescription():
  662.                 pass
  663.             return str(test)
  664.         else:
  665.             return str(test)
  666.  
  667.     
  668.     def startTest(self, test):
  669.         TestResult.startTest(self, test)
  670.         if self.showAll:
  671.             self.stream.write(self.getDescription(test))
  672.             self.stream.write(' ... ')
  673.         
  674.  
  675.     
  676.     def addSuccess(self, test):
  677.         TestResult.addSuccess(self, test)
  678.         if self.showAll:
  679.             self.stream.writeln('ok')
  680.         elif self.dots:
  681.             self.stream.write('.')
  682.         
  683.  
  684.     
  685.     def addError(self, test, err):
  686.         TestResult.addError(self, test, err)
  687.         if self.showAll:
  688.             self.stream.writeln('ERROR')
  689.         elif self.dots:
  690.             self.stream.write('E')
  691.         
  692.  
  693.     
  694.     def addFailure(self, test, err):
  695.         TestResult.addFailure(self, test, err)
  696.         if self.showAll:
  697.             self.stream.writeln('FAIL')
  698.         elif self.dots:
  699.             self.stream.write('F')
  700.         
  701.  
  702.     
  703.     def printErrors(self):
  704.         if self.dots or self.showAll:
  705.             self.stream.writeln()
  706.         
  707.         self.printErrorList('ERROR', self.errors)
  708.         self.printErrorList('FAIL', self.failures)
  709.  
  710.     
  711.     def printErrorList(self, flavour, errors):
  712.         for test, err in errors:
  713.             self.stream.writeln(self.separator1)
  714.             self.stream.writeln('%s: %s' % (flavour, self.getDescription(test)))
  715.             self.stream.writeln(self.separator2)
  716.             self.stream.writeln('%s' % err)
  717.         
  718.  
  719.  
  720.  
  721. class TextTestRunner:
  722.     '''A test runner class that displays results in textual form.
  723.  
  724.     It prints out the names of tests as they are run, errors as they
  725.     occur, and a summary of the results at the end of the test run.
  726.     '''
  727.     
  728.     def __init__(self, stream = sys.stderr, descriptions = 1, verbosity = 1):
  729.         self.stream = _WritelnDecorator(stream)
  730.         self.descriptions = descriptions
  731.         self.verbosity = verbosity
  732.  
  733.     
  734.     def _makeResult(self):
  735.         return _TextTestResult(self.stream, self.descriptions, self.verbosity)
  736.  
  737.     
  738.     def run(self, test):
  739.         '''Run the given test case or test suite.'''
  740.         result = self._makeResult()
  741.         startTime = time.time()
  742.         test(result)
  743.         stopTime = time.time()
  744.         timeTaken = float(stopTime - startTime)
  745.         result.printErrors()
  746.         self.stream.writeln(result.separator2)
  747.         run = result.testsRun
  748.         if not run != 1 and 's':
  749.             pass
  750.         self.stream.writeln('Ran %d test%s in %.3fs' % (run, '', timeTaken))
  751.         self.stream.writeln()
  752.         if not result.wasSuccessful():
  753.             self.stream.write('FAILED (')
  754.             (failed, errored) = map(len, (result.failures, result.errors))
  755.             if failed:
  756.                 self.stream.write('failures=%d' % failed)
  757.             
  758.             if errored:
  759.                 if failed:
  760.                     self.stream.write(', ')
  761.                 
  762.                 self.stream.write('errors=%d' % errored)
  763.             
  764.             self.stream.writeln(')')
  765.         else:
  766.             self.stream.writeln('OK')
  767.         return result
  768.  
  769.  
  770.  
  771. class TestProgram:
  772.     '''A command-line program that runs a set of tests; this is primarily
  773.        for making test modules conveniently executable.
  774.     '''
  775.     USAGE = "Usage: %(progName)s [options] [test] [...]\n\nOptions:\n  -h, --help       Show this message\n  -v, --verbose    Verbose output\n  -q, --quiet      Minimal output\n\nExamples:\n  %(progName)s                               - run default set of tests\n  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'\n  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething\n  %(progName)s MyTestCase                    - run all 'test*' test methods\n                                               in MyTestCase\n"
  776.     
  777.     def __init__(self, module = '__main__', defaultTest = None, argv = None, testRunner = None, testLoader = defaultTestLoader):
  778.         if type(module) == type(''):
  779.             self.module = __import__(module)
  780.             for part in string.split(module, '.')[1:]:
  781.                 self.module = getattr(self.module, part)
  782.             
  783.         else:
  784.             self.module = module
  785.         if argv is None:
  786.             argv = sys.argv
  787.         
  788.         self.verbosity = 1
  789.         self.defaultTest = defaultTest
  790.         self.testRunner = testRunner
  791.         self.testLoader = testLoader
  792.         self.progName = os.path.basename(argv[0])
  793.         self.parseArgs(argv)
  794.         self.runTests()
  795.  
  796.     
  797.     def usageExit(self, msg = None):
  798.         if msg:
  799.             print msg
  800.         
  801.         print self.USAGE % self.__dict__
  802.         sys.exit(2)
  803.  
  804.     
  805.     def parseArgs(self, argv):
  806.         import getopt
  807.         
  808.         try:
  809.             (options, args) = getopt.getopt(argv[1:], 'hHvq', [
  810.                 'help',
  811.                 'verbose',
  812.                 'quiet'])
  813.             for opt, value in options:
  814.                 if opt in ('-h', '-H', '--help'):
  815.                     self.usageExit()
  816.                 
  817.                 if opt in ('-q', '--quiet'):
  818.                     self.verbosity = 0
  819.                 
  820.                 if opt in ('-v', '--verbose'):
  821.                     self.verbosity = 2
  822.                     continue
  823.             
  824.             if len(args) == 0 and self.defaultTest is None:
  825.                 self.test = self.testLoader.loadTestsFromModule(self.module)
  826.                 return None
  827.             
  828.             if len(args) > 0:
  829.                 self.testNames = args
  830.             else:
  831.                 self.testNames = (self.defaultTest,)
  832.             self.createTests()
  833.         except getopt.error:
  834.             msg = None
  835.             self.usageExit(msg)
  836.  
  837.  
  838.     
  839.     def createTests(self):
  840.         self.test = self.testLoader.loadTestsFromNames(self.testNames, self.module)
  841.  
  842.     
  843.     def runTests(self):
  844.         if self.testRunner is None:
  845.             self.testRunner = TextTestRunner(verbosity = self.verbosity)
  846.         
  847.         result = self.testRunner.run(self.test)
  848.         sys.exit(not result.wasSuccessful())
  849.  
  850.  
  851. main = TestProgram
  852. if __name__ == '__main__':
  853.     main(module = None)
  854.  
  855.